package mysql

import (
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"errors"
	"go_wep_demo/models"
)

const encodeKey = "hellogolang"

// CheckUserNameIsIsSet 检查用户名是否存在
func CheckUserNameIsIsSet(username string) (err error) {
	sql := "select count(user_id) from user where username = ?"
	var count int
	err = db.Get(&count, sql, username)
	if err != nil {
		return err
	}
	if count > 0 {
		return errors.New("用户名已存在")
	}
	return nil
}

// FindUserByUsername 根据用户名查找用户
func FindUserByUsername(username string) (user models.User, err error) {
	sqlStr := "select user_id,username,password,gender,email from user where username = ?"
	err = db.Get(&user, sqlStr, username)
	if err == sql.ErrNoRows {
		return user, errors.New("用户不存在")
	}
	if err != nil {
		return user, err
	}
	return user, nil
}

// InsertUser新增一条用户记录
func InsertUser(user *models.User) error {
	user.Password = EncodePwd(user.Password)
	sql := "insert into user(user_id,username,password,email) values(?,?,?,?)"
	_, err := db.Exec(sql, user.UserId, user.Username, user.Password, user.Email)
	return err
}

// EncodePwd 密码加密
func EncodePwd(pwd string) string {
	h := md5.New()
	h.Write([]byte(encodeKey))
	newPwd := h.Sum([]byte(pwd))
	return hex.EncodeToString(newPwd)
}
